package C037;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: C03
 * Package: C037
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/23 15:58
 * @Version 1.0
 * @Since 1.0
 */
public class C03 {
    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(5);
        TreeNode treeNode2 = new TreeNode(4);
        TreeNode treeNode3 = new TreeNode(8);
        TreeNode treeNode4 = new TreeNode(11);
        TreeNode treeNode5 = new TreeNode(13);
        TreeNode treeNode6 = new TreeNode(4);
        TreeNode treeNode7 = new TreeNode(7);
        TreeNode treeNode8 = new TreeNode(2);
        TreeNode treeNode9 = new TreeNode(5);
        TreeNode treeNode10 = new TreeNode(1);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode3.left = treeNode5;
        treeNode3.right = treeNode6;
        treeNode4.left = treeNode7;
        treeNode4.right = treeNode8;
        treeNode6.left = treeNode9;
        treeNode6.right = treeNode10;
        C03 c03 = new C03();
        System.out.println(c03.pathSum(treeNode1, 22));
    }

    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    //
    public List<List<Integer>> ans = new ArrayList<>();
    public List<Integer> mid = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {

        process(root, targetSum);
        return ans;
    }

    private void process(TreeNode root, int targetSum) {
        if(root == null) {
            return;
        }
        targetSum -= root.val;
        mid.add(root.val);
        if(targetSum == 0 && root.left == null && root.right == null) {
            ans.add(copyList(mid));
            mid.remove(mid.size() - 1);
            return;
        }
        process(root.left, targetSum);
        process(root.right, targetSum);
        mid.remove(mid.size() - 1);
    }

    private static List<Integer> copyList(List<Integer> mid) {
        if(mid == null){
            return null;
        }
        return new ArrayList<>(mid);
    }

}
